package org.homeworkteam.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.homeworkteam.bean.FavoriteVideo;
import org.homeworkteam.bean.PurchasedVideo;
import org.homeworkteam.bean.Teachers;
import org.homeworkteam.bean.Video;
import org.homeworkteam.mapper.FavoriteVideoMapper;
import org.homeworkteam.mapper.PurchasedVideoMapper;
import org.homeworkteam.mapper.TeacherMapper;
import org.homeworkteam.mapper.VideoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class VideoService extends ServiceImpl<VideoMapper, Video> {
    @Autowired
    private PurchasedVideoMapper purchasedVideoMapper;

    @Autowired
    private FavoriteVideoMapper favoriteVideoMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    // 视频URL的固定前缀
    private static final String VIDEO_URL_PREFIX = "http://localhost:8007/video/get?url=";

    /**
     * 获取分页视频信息列表
     *
     * @param pageNum  当前页码
     * @param pageSize 每页大小
     * @return 包含分页数据的 List
     */
    public List<Video> getVideosInfo(int pageNum, int pageSize) {
        Page<Video> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("video_id");
        return this.baseMapper.selectPage(page, queryWrapper).getRecords().stream().map(video -> {
            video.setVideoUrl(VIDEO_URL_PREFIX + video.getVideoUrl());
            Teachers teacher = teacherMapper.selectById(video.getTeacherId());
            video.setTeacher(teacher);
            return video;
        }).collect(Collectors.toList());
    }

    /**
     * 根据视频ID获取视频信息
     *
     * @param videoId 视频ID
     * @return 视频信息
     */
    public Video getVideoInfo(long videoId) {
        Video video = this.baseMapper.selectById(videoId);
        if (video == null) {
            throw new RuntimeException("Video not found with id: " + videoId);
        }
        video.setVideoUrl(VIDEO_URL_PREFIX + video.getVideoUrl());
        Teachers teacher = teacherMapper.selectById(video.getTeacherId());
        video.setTeacher(teacher);
        return video;
    }

    /**
     * 添加新视频
     *
     * @return 是否成功
     */
    public boolean addVideo() {
        Video video = new Video();
        video.setVideoUrl("666.mp4");
        video.setPrice(50.00);
        video.setOldPrice(60.00);
        video.setTeacherId(1);
        video.setStatus("1");
        video.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        video.setVideoImg("default_img.jpg");
        return this.save(video);
    }

    /**
     * 根据用户ID查询已购买视频ID列表
     *
     * @param userId 用户ID
     * @return 已购买视频ID列表
     */
    public List<Integer> getPurchasedVideosByUserId(Long userId) {
        // 创建查询条件
        QueryWrapper<PurchasedVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        // 查询数据并提取 videoId
        return purchasedVideoMapper.selectList(queryWrapper)
                .stream()
                .map(PurchasedVideo::getVideoId) // 使用 PurchasedVideo 的 getter 方法
                .collect(Collectors.toList());
    }


    /**
     * 根据用户ID查询收藏视频ID列表
     *
     * @param userId 用户ID
     * @return 收藏视频ID列表
     */
    public List<FavoriteVideo> getFavoriteVideosByUserId(Long userId) {
        // 构建查询条件
        QueryWrapper<FavoriteVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        // 查询收藏的视频记录，直接返回 List<FavoriteVideo>
        return favoriteVideoMapper.selectList(queryWrapper);
    }

    /**
     * 添加收藏视频
     *
     * @param favoriteVideo 收藏视频对象
     * @return 是否添加成功
     */
    public boolean addFavoriteVideo(FavoriteVideo favoriteVideo) {
        int rows = favoriteVideoMapper.insert(favoriteVideo);
        return rows > 0;
    }

    /**
     * 删除收藏视频
     *
     * @param favoriteVideo 收藏视频对象
     * @return 是否删除成功
     */
    public boolean delFavoriteVideo(FavoriteVideo favoriteVideo) {
        // 构建查询条件，仅根据 userId 和 videoId 删除
        QueryWrapper<FavoriteVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", favoriteVideo.getUserId())
                .eq("video_id", favoriteVideo.getVideoId());

        // 执行删除操作
        int rows = favoriteVideoMapper.delete(queryWrapper);
        return rows > 0; // 返回是否删除成功
    }

}
